import { Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { compareSync } from 'bcryptjs';
import { User } from 'libs/db/entity/user.entity';
import { Villager } from 'libs/db/entity/villager.entity';

@Injectable()
export class AuthService {
  constructor(
    @InjectRepository(User) private readonly userRepo,
    @InjectRepository(Villager) private readonly villagerRepo,
    private readonly jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    const user = await this.userRepo
      .createQueryBuilder('user')
      .leftJoinAndSelect("user.area", "area")
      .leftJoinAndSelect("user.town", "town")
      .leftJoinAndSelect("user.village", "village")
      .addSelect('user.password')
      .where('user.username = :username', { username })
      .getOne();
    if (user && compareSync(password, user.password)) {
      const { password, ...result } = user;
      console.log(result);
      return result;
    }
    return null;
  }

  async validateVillager(username: string, password: string): Promise<any> {
    const villager = await this.villagerRepo
      .createQueryBuilder('villager')
      .addSelect('villager.password')
      .where('villager.account = :username', { username })
      .getOne();

    if (villager && compareSync(password, villager.password)) {
      const { password, ...result } = villager;
      console.log(result);
      return result;
    }
    return null;
  }

  async login(user: Villager | User) {
    console.log(user, `-------------------user`)
    // const userId = user;
    return {
      message: "登录成功",
      access_token: this.jwtService.sign({
        id: user.id
      }),
    };
  }

  async getIdByUsername(username: string) {
    const user = await this.userRepo
      .createQueryBuilder('user')
      .leftJoinAndSelect("user.area", "area")
      .leftJoinAndSelect("user.town", "town")
      .leftJoinAndSelect("user.village", "village")
      .where('user.username = :username', { username })
      .getOne();
    if (user) {
      return user;
    }
    return null;
  }

  async getUserById(id: Number) {
    const user = await this.userRepo
      .createQueryBuilder('user')
      .leftJoinAndSelect("user.area", "area")
      .leftJoinAndSelect("user.town", "town")
      .leftJoinAndSelect("user.village", "village")
      .where('user.id = :id', { id })
      .getOne();
    if (user) {
      return user;
    }
    return null;
  }
}
